<template>
  <div class="tree-panel">
    <!-- 使用v-loading替代自定义加载动画 -->
    <div v-loading="loading" class="tree-list-container">
      <!-- 仿树列表 -->
      <div class="tree-list">
        <div v-for="group in list" :key="group.id" class="tree-group">
          <div
            class="tree-node tree-node--primary"
            :class="{
              'tree-node--expanded': group.expand
            }"
            @click="selectNode(group)"
          >
            <div class="tree-node__content">
              <img src="@/assets/imgs/data/seal.svg" class="tree-node__icon" />
              <span class="tree-node__label">{{ group.label }}</span>
              <!-- <span class="tree-node__count">{{ group.count }}</span> -->
            </div>
            <div class="tree-node__arrow">
              <img
                src="@/assets/imgs/data/arrow.svg"
                :class="{ 'tree-node__arrow--rotated': !group.expand }"
                @click="toggle(group)"
              />
            </div>
          </div>

          <!-- 第二级子列表 -->
          <transition name="tree-sub" mode="out-in">
            <div v-show="group.expand" class="tree-sub-list">
              <template v-for="child in group.children" :key="child.id">
                <div
                  class="tree-node tree-node--secondary"
                  :class="{ 'tree-node--selected': selectedNodeId === child.id }"
                  @click="selectNode(child)"
                >
                  <span class="tree-node__label">{{ child.label }}</span>
                  <!-- <span class="tree-node__count">{{ child.count }}</span> -->

                  <!-- 第三级节点箭头 -->
                  <div
                    v-if="child.children && child.children.length > 0"
                    class="tree-node__arrow"
                    @click.stop="toggle(child)"
                  >
                    <img
                      src="@/assets/imgs/data/arrow.svg"
                      :class="{ 'tree-node__arrow--rotated': !child.expand }"
                    />
                  </div>
                </div>

                <!-- 第三级子列表 -->
                <div v-if="child.children && child.children.length > 0">
                  <transition name="tree-sub" mode="out-in">
                    <div v-show="child.expand" class="tree-sub-list tree-sub-list--level2">
                      <template v-for="grandChild in child.children" :key="grandChild.id">
                        <div
                          class="tree-node tree-node--tertiary"
                          :class="{ 'tree-node--selected': selectedNodeId === grandChild.id }"
                          @click="selectNode(grandChild)"
                        >
                          <span class="tree-node__label">{{ grandChild.label }}</span>
                          <!-- <span class="tree-node__count">{{ grandChild.count }}</span> -->

                          <!-- 第四级节点箭头 -->
                          <div
                            v-if="grandChild.children && grandChild.children.length > 0"
                            class="tree-node__arrow"
                            @click.stop="toggle(grandChild)"
                          >
                            <img
                              src="@/assets/imgs/data/arrow.svg"
                              :class="{ 'tree-node__arrow--rotated': !grandChild.expand }"
                            />
                          </div>
                        </div>

                        <!-- 第四级子列表 -->
                        <div v-if="grandChild.children && grandChild.children.length > 0">
                          <transition name="tree-sub" mode="out-in">
                            <div
                              v-show="grandChild.expand"
                              class="tree-sub-list tree-sub-list--level3"
                            >
                              <div
                                v-for="greatGrandChild in grandChild.children"
                                :key="greatGrandChild.id"
                                class="tree-node tree-node--quaternary"
                                :class="{
                                  'tree-node--selected': selectedNodeId === greatGrandChild.id
                                }"
                                @click="selectNode(greatGrandChild)"
                              >
                                <span class="tree-node__label">{{ greatGrandChild.label }}</span>
                                <!-- <span class="tree-node__count">{{ greatGrandChild.count }}</span> -->
                              </div>
                            </div>
                          </transition>
                        </div>
                      </template>
                    </div>
                  </transition>
                </div>
              </template>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits } from 'vue'
import * as PortalApi from '@/api/portal'

const emit = defineEmits(['node-click'])

interface Node {
  id: number
  label: string
  count?: number
  icon?: string
  children?: Node[]
  expand?: boolean
}

interface Group extends Node {
  children: Node[]
  expand?: boolean
}

const selectedNodeId = ref<number | null>(null)
const list = ref<Group[]>([])
const loading = ref(true) // 加载状态
const expandedNodes = ref<Record<number, boolean>>({})

const toggle = (node: any) => {
  if (node.children && node.children.length > 0) {
    node.expand = !node.expand
    // 保存展开状态
    expandedNodes.value[node.id] = node.expand
  }
}

const selectNode = (node: Node) => {
  selectedNodeId.value = node.id
  // 发射节点点击事件，传递menuId
  emit('node-click', node.id)
}

const getTree = async () => {
  loading.value = true // 开始加载
  try {
    const res = await PortalApi.getCatalogTree()
    if (res) {
      // 构建树形结构
      const treeData = buildTreeFromApiData(res)
      list.value = treeData
      // console.log('list', list.value)
    }
  } catch (error) {
    console.error('获取数据分类失败:', error)
    // 可以在这里添加错误处理逻辑
  } finally {
    loading.value = false // 加载结束，无论成功或失败
  }
}

const buildTreeFromApiData = (apiData: any[]): Group[] => {
  // 使用实际的API数据结构构建树形结构
  // classifySj字段表示父节点ID，'0'表示根节点

  // 递归构建树形结构的辅助函数
  // 添加level参数来跟踪当前节点的层级
  const buildTreeRecursive = (parentId: string | number, level: number = 0): Node[] => {
    const children: Node[] = []

    // 查找所有classifySj等于当前父级ID的项
    const directChildren = apiData.filter((item) => item.classifySj === parentId.toString())

    directChildren.forEach((item) => {
      const node: Node = {
        id: item.id,
        label: item.menuName,
        count: item.catalogNumber || 0,
        // 默认展开前两级节点，从第三级开始默认折叠
        expand:
          expandedNodes.value[item.id] !== undefined ? expandedNodes.value[item.id] : level < 2 // 只展开前两级
      }

      // 递归查找当前节点的子节点，层级加1
      const childNodes = buildTreeRecursive(item.id, level + 1)
      if (childNodes.length > 0) {
        node.children = childNodes
      }

      children.push(node)
    })

    return children
  }

  // 从根节点（classifySj为'0'）开始构建树，根节点层级为0
  const rootNodes = buildTreeRecursive('0', 0)

  return rootNodes
}

onMounted(() => {
  // 初始化时获取数据分类
  getTree()
})
</script>

<style scoped lang="scss">
$primary-blue: #009eff;
$primary-text: #303133;
$secondary-text: #909399;
$border-color: #ebeef5;
$white: #fff;
$hover-bg: #f5f7fa;

.tree-panel {
  display: flex;
  flex-direction: column;
  padding: 20px;
  font-size: 14px;
  color: $primary-text;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  min-height: 400px; /* 确保有足够空间显示加载动画 */
}

// 移除自定义加载动画样式

// 调整内容容器样式
.tree-list-container {
  min-height: 400px;
}

.tree-list {
  flex: 1;
  overflow: auto;

  .tree-group + .tree-group {
    margin-top: 12px;
  }
}

.tree-node {
  display: flex;
  align-items: center;
  min-height: 40px;
  cursor: pointer;
  user-select: none;
  border-radius: 6px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 8px 12px;
  margin: 2px 0;
  font-size: 18px;

  &:hover {
    background: rgba($primary-blue, 0.08);
  }

  &--primary {
    font-weight: 600;
    border: 1px solid $border-color;
    background: $white;
    color: $primary-text; // 第一级节点文字为黑色

    &:hover {
      border-color: $primary-blue;
      box-shadow: 0 2px 8px rgba($primary-blue, 0.12);
    }

    &.tree-node--expanded {
      background: rgba($primary-blue, 0.04);
      border-color: $primary-blue;
    }
  }

  &--secondary {
    padding-left: 44px;
    // color: $secondary-text;
    font-weight: 600;
    border-radius: 8px;
    overflow: hidden;
    color: $primary-text; // 第二级节点文字为黑色
    font-size: 17px;

    &:hover {
      color: $primary-text;
      background: rgba($primary-blue, 0.06);
    }

    // 选中状态样式
    &.tree-node--selected {
      background: $primary-blue !important;
      color: $white !important;

      .tree-node__count {
        color: $white !important;
      }

      &:hover {
        background: darken($primary-blue, 5%) !important;
      }
    }
  }

  &--tertiary {
    padding-left: 68px;
    // color: $secondary-text;
    color: $primary-text; // 第二级节点文字为黑色
    font-weight: 400;
    border-radius: 8px;
    overflow: hidden;
    font-size: 16px;

    &:hover {
      color: $primary-text;
      background: rgba($primary-blue, 0.06);
    }

    &.tree-node--selected {
      background: $primary-blue !important;
      color: $white !important;

      .tree-node__count {
        color: $white !important;
      }

      &:hover {
        background: darken($primary-blue, 5%) !important;
      }
    }
  }

  &--quaternary {
    padding-left: 92px;
    color: $secondary-text;
    font-weight: 400;
    border-radius: 8px;
    overflow: hidden;
    font-size: 15px;

    &:hover {
      color: $primary-text;
      background: rgba($primary-blue, 0.06);
    }

    &.tree-node--selected {
      background: $primary-blue !important;
      color: $white !important;

      .tree-node__count {
        color: $white !important;
      }

      &:hover {
        background: darken($primary-blue, 5%) !important;
      }
    }
  }

  &__content {
    display: flex;
    align-items: center;
    flex: 1;
    gap: 8px;
  }

  &__icon {
    width: 20px;
    height: 20px;
    object-fit: contain;
  }

  &__label {
    flex: 1;
    transition: color 0.2s ease;
  }

  &__count {
    color: $secondary-text;
    font-size: 13px;
    font-weight: 500;
    padding-left: 8px;
    min-width: 60px;
    text-align: right;
    transition: color 0.2s ease;
  }

  &__arrow {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);

    img {
      width: 16px;
      height: 16px;
      transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);

      &.tree-node__arrow--rotated {
        transform: rotate(-180deg);
      }
    }
  }

  &--selected {
    .tree-node__arrow img {
      filter: brightness(0) invert(1); // 将SVG图片变为白色
    }
  }
}

.tree-sub-list {
  overflow: hidden;

  &--level2 {
    .tree-node {
      padding-left: 68px;
    }
  }

  &--level3 {
    .tree-node {
      padding-left: 92px;
    }
  }
}

// 优化的CSS过渡动画 - 解决卡顿问题
.tree-sub-enter-active,
.tree-sub-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, opacity; // 硬件加速优化
}

.tree-sub-enter-active {
  transition-delay: 0.05s;
}

.tree-sub-enter-from {
  opacity: 0;
  transform: translateY(-8px) scaleY(0.8);
  transform-origin: top center;
}

.tree-sub-enter-to {
  opacity: 1;
  transform: translateY(0) scaleY(1);
  transform-origin: top center;
}

.tree-sub-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, opacity; // 硬件加速优化
}

.tree-sub-leave-from {
  opacity: 1;
  transform: translateY(0) scaleY(1);
  transform-origin: top center;
}

.tree-sub-leave-to {
  opacity: 0;
  transform: translateY(-8px) scaleY(0.8);
  transform-origin: top center;
}

// 箭头旋转动画优化
.tree-node__arrow {
  transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  will-change: transform; // 硬件加速优化
}

.tree-node__arrow img {
  transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  will-change: transform; // 硬件加速优化
}

// 为展开状态添加更平滑的过渡
.tree-node--expanded {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

// 优化容器性能
.tree-list {
  contain: layout style paint; // 性能优化
}

.tree-group {
  contain: layout style paint; // 性能优化
}
</style>
